package com.xiaoxie.system.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;

/**
 * @author xiaoxie
 * @create 2025-01-19
 * @Version 1.0。0
 * @Description: 动态数据源管理类，用于管理和切换数据源
 */
public class DynamicDataSourceManager extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public DynamicDataSourceManager(DruidDataSource druidDataSource,
                                    Map<Object,Object> targetDataSources) {
        super.setDefaultTargetDataSource(druidDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return contextHolder.get();
    }

    public static void setDataSource(String sourceName) {
        contextHolder.set(sourceName);
    }

    public static void clearDataSource() {
        contextHolder.remove();
    }
}
